﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zatify.WebUI.Infrastructure;
using Zatify.Domain.Abstract;
using Zatify.Domain.Data;
using Zatify.WebUI.Admin.Models;
using Zatify.WebUI.Infrastructure.Filters;
using Zatify.WebUI.Infrastructure.Absrtact;
using Zatify.WebUI.Models;

namespace Zatify.WebUI.Areas.Admin.Controllers
{
    [ZatifyAdminAuthorizeAttribute]
    [Utils.MyRequireHttps]
    public class SystemUsersController : AdminBaseController
    {
        private const int PageSize = 20;

        private IZatifyRepository repository;

        protected override AdminModules AdminModule
        {
            get
            {
                return AdminModules.SystemUsers;
            }
        }

        public SystemUsersController(IZatifyRepository repository, IZatifyAuthProvider authProvider)
        //: base(authProvider)
        {
            this.repository = repository;
        }

        public ActionResult List(int page = 1, int id = 0, SearchSystemUserViewModel searchUserModel = null)
        {
            Func<SystemUser, bool> searchByUserId = (u => !String.IsNullOrEmpty(searchUserModel.SystemUserID) ? u.Login.Trim().ToLower().Contains(searchUserModel.SystemUserID.Trim().ToLower()) : true);
            Func<SystemUser, bool> searchByEmail = (u => !String.IsNullOrEmpty(searchUserModel.Email) ? u.Email.Trim().ToLower().Contains(searchUserModel.Email.Trim().ToLower()) : true);
            Func<SystemUser, bool> searchByPhone = (u => !String.IsNullOrEmpty(searchUserModel.Phone) ? u.Phone.Trim().ToLower().Contains(searchUserModel.Phone.Trim().ToLower()) : true);

            var users = repository.SystemUsers.Where(searchByUserId).Where(searchByEmail).Where(searchByPhone).Skip((page - 1) * PageSize).Take(PageSize).ToList();

            var model = new SystemUsersListViewModel()
            {
                CurrentUserRole = User.UserRole,

                SelectedSystemUserID = id,
                Users = users,
                PagingInfo = new PagingInfo()
                {
                    TotalItems = repository.SystemUsers.Where(searchByUserId).Where(searchByEmail).Where(searchByPhone).Count(),
                    ItemsPerPage = PageSize,
                    CurrentPage = page,
                },
                SearchModel = searchUserModel
            };

            var pages = new List<SelectListItem>();

            for (int i = 1; i <= model.PagingInfo.TotalPages; i++)
                pages.Add(new SelectListItem() { Text = i.ToString(), Value = i.ToString(), Selected = (i == page) });

            ViewData["pagesCount"] = pages;

            var roles = new List<SelectListItem>();
            roles.Add(new SelectListItem() { Text = "Administraotor", Value = "ADMIN" });
            roles.Add(new SelectListItem() { Text = "User", Value = "USER" });

            ViewData["Roles"] = roles;

            return View(model);
        }

        [HttpPost]
        public ActionResult Update(SystemUser user, SearchSystemUserViewModel searchSystemUserModel, int page = 1)
        {
            user.Email = user.Email ?? String.Empty;
            user.Phone = user.Phone ?? String.Empty;

            if (this.ModelState.IsValid)
            {
                repository.SystemUserUpdate(user);
                return RedirectToAction("List", new
                {
                    page = page,
                    //searchSystemUserModel = searchSystemUserModel
                    SystemUserID = searchSystemUserModel.SystemUserID,
                    Email = searchSystemUserModel.Email,
                    Phone = searchSystemUserModel.Phone
                });
            }
            else
            {
                ViewData["Error"] = "Error occured during System User save";
            }

            return View("List", new SystemUsersListViewModel()
            {
                SelectedSystemUserID = user.SystemUserId,
                Users = repository.SystemUsers,
                PagingInfo = new PagingInfo()
                {
                    TotalItems = repository.SystemUsers.Count(),
                    ItemsPerPage = PageSize,
                    CurrentPage = 1,
                }
            });
        }

        [HttpPost]
        public ActionResult Add(AddNewSystemUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                repository.SystemUserAdd(new SystemUser()
                {
                    Login = model.UserID.Trim(),
                    Password = model.Password,
                    Email = !String.IsNullOrWhiteSpace(model.Email) ? model.Email : String.Empty,
                    Phone = !String.IsNullOrWhiteSpace(model.Phone) ? model.Phone : String.Empty,
                    Role = model.Role
                });

                return RedirectToAction("List");
            }
            else
            {
                return Json(false);
            }
        }

        public JsonResult UserIDUnique(string userId)
        {
            if (repository.SystemUsers.Any(u => u.Login.Trim().ToLower() == userId.Trim().ToLower()))
                return Json(userId + " is already in use.", JsonRequestBehavior.AllowGet);
            else
                return Json(true, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangeSystemUserPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                repository.SystemUserChangePassword(model.UserID, model.Password);

                return RedirectToAction("List");
            }
            else
            {
                return Json(false);
            }
        }

        public ActionResult Delete(int id)
        {
            if (id > 0)
                repository.SystemUserDeleteById(id);

            return RedirectToAction("List");
        }

        public ActionResult DeleteUsers(int[] usersIds)
        {
            if (usersIds != null && usersIds.Length > 0)
            {
                repository.SystemUsersDeleteByIds(usersIds);
                return Json(new { status = true });
            }
            else
            {
                return Json(new { status = false });
            }
        }

        public ActionResult ChangeUserStatus(int id, int activate)
        {
            if (activate == 0 || activate == 1)
                repository.SystemUserChangeStatus(id, (activate == 1));

            return RedirectToAction("List");
        }

        public ActionResult ChangeUsersStatus(int[] usersIds, int activate)
        {
            if ((usersIds != null && usersIds.Length > 0))
            {
                if (activate == 0 || activate == 1)
                    repository.SystemUsersChangeStatus(usersIds, activate == 1);

                return Json(new { status = true });
            }
            else
            {
                return Json(new { status = false });
            }
        }
    }
}
